package com.kandinfo.survey.weixin.service.impl;

import java.util.Date;

import org.apache.shiro.authc.credential.PasswordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kandinfo.base.common.converter.ConverterService;
import com.kandinfo.base.common.util.Constants;
import com.kandinfo.base.security.SecurityContext;
import com.kandinfo.base.security.domain.User;
import com.kandinfo.base.security.domain.UserRole;
import com.kandinfo.base.security.dto.UserDto;
import com.kandinfo.base.security.service.UserRoleService;
import com.kandinfo.base.security.service.UserService;
import com.kandinfo.survey.weixin.service.WxAuthService;


@Service
public class WxAuthServiceImpl implements WxAuthService {

	@SuppressWarnings("unused")
    private final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private PasswordService passwordService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserRoleService userRoleService;

	@Override
	public boolean registWxUser(UserDto adminUserDto) {
		String[] roles = adminUserDto.getRoleIds().split(",");
        User user = ConverterService.convert(adminUserDto, User.class);
        String pwd = passwordService.encryptPassword(getPassword(user.getPassword(), user.getUsername()));
        user.setPassword(pwd);
        user.setStatus(Constants.USER_ACTIVE);
        User newUser = userService.saveUser(user);
        Long userId = newUser.getId();
        int rolesLength = roles == null ? 0 : roles.length;
        if (rolesLength > 0) {
            for (int i = 0; i < roles.length; i++) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(Long.valueOf(roles[i].trim()));
                userRole.setCreateTs(new Date());
                userRole.setCreateBy(SecurityContext.getInstance().getCurrentUserId());
                userRoleService.save(userRole);
            }
        }
		return true;
	}
	
	private String getPassword(String pass, String username) {
        return pass + Integer.toString(username.substring(0, 4).hashCode());
    }
	
	

	

}
